package com.ncbee.base.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ncbee.base.config.shiro.annotation.RequiresExtPermissions;
import com.ncbee.base.model.entity.User;
import com.ncbee.base.model.entity.UserRole;
import com.ncbee.base.model.vo.BaseQuery;
import com.ncbee.base.model.vo.Result;
import com.ncbee.base.model.vo.tableVo.UserVo;
import com.ncbee.base.service.UserRoleService;
import com.ncbee.base.service.UserService;
import com.ncbee.base.util.StringUtils;
import com.ncbee.base.web.base.BaseController;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author youdianyun
 * @since 2018-11-23
 */
@Controller
@RequestMapping("/user")
@RequiresExtPermissions("user:")
public class UserController extends BaseController<User> {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    protected IService<User> getTargetService(){
        return userService;
    }

    @Override
    public String getListPageUrl() {
        return "user/listPage";
    }

    @Override
    protected String getAddPageUrl() {
        return "user/addPage";
    }

    @Override
    protected String getEditPageUrl() {
        return "user/editPage";
    }

    @ResponseBody
    @RequestMapping("userLogout")
    public Object userLogout(HttpSession session){
        SecurityUtils.getSubject().logout();//执行退出方法
        Result result=renderSuccess();
        result.setMsg("退出成功，两秒之后回到登录界面");
        return result;
    }
    @ResponseBody
    @RequestMapping("/list")
    public Object list(HttpServletRequest request,BaseQuery<User> baseQuery){
        IPage<UserVo> page=new Page<UserVo>();
        if(baseQuery.getPage()!=null){
            page.setCurrent(baseQuery.getPage());
        }if(baseQuery.getLimit()!=null){
            page.setSize(baseQuery.getLimit());
        }
        page=userService.getUserList(page,baseQuery);
        return renderPage(page);
    }
    @RequestMapping("/grantPage")
    public String grantPage(Long id,HttpServletRequest request){
     //从用户角色表中，查询当前用户所拥有的所有角色
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",id);
        List<UserRole> list=userRoleService.list(queryWrapper);
        StringBuffer stringBuffer=new StringBuffer("");
        if(!CollectionUtils.isEmpty(list)){
            int index=0;
            for(UserRole userRole:list){
                ++index;
                if(index!=list.size()){
                    stringBuffer.append(""+userRole.getRoleId());
                    stringBuffer.append(",");
                }else{
                    stringBuffer.append(""+userRole.getRoleId());
                }
            }
        }
        request.setAttribute("userId",id);
        request.setAttribute("userRoleStr",stringBuffer.toString());
     return "user/grantPage";
    }

    /**
     * 用户修改密码
     * @return
     */
    @RequestMapping("updatePasswordPage")
    public String userUpdatePassword(){
     return "user/updatePasswordPage";
    }
    /**
     *
     * @param userId
     * @param roleStr
     * @return
     */
    @ResponseBody
    @RequestMapping("grantRoleToUser")
    public Object grantRoleToUser(@NotNull Long userId, String roleStr){
        boolean flag=userService.grantRoleToUser(userId,roleStr);
        if(flag){
            return renderSuccess();
        }
    return renderError("分配失败");
    }
    /**
     * 重置用户密码
     */
    @ResponseBody
    @RequestMapping("resetUserPassword")
    public Object resetUserPassword(Long userId){
       boolean flag=userService.resetUserPassword(userId);
       if(flag){
           return renderSuccess();
       }
    return renderError("重置失败");
    }
    @ResponseBody
    @RequestMapping("updatePassword")
    public Object updatePassword(String password){
     Long userId=getCurrentUserId();
     boolean flag=userService.updateUserPassword(userId,password);
     if(flag){//
         SecurityUtils.getSubject().logout();
         return renderSuccess("更新成功请重新登录");
     }
     return renderError();
    }
    /**
     * 保存用户之前做一些操作
     * @param request
     * @param entity
     */
    @Override
    protected void beforeSave(HttpServletRequest request, User entity){
        //设置注册时间
        entity.setRegisterTime(LocalDateTime.now());
        //设置创建时间
        entity.setCreateTime(LocalDateTime.now());
        //设置密码散列
        String rawPassword=entity.getPassword();
        //获取二次散列之后密码
        String md5Password= StringUtils.getCustomMD5Str(rawPassword);
        entity.setPassword(md5Password);
    }

    /**
     *
     * @param request
     * @param entity
     */
    @Override
    protected void beforeUpdate(HttpServletRequest request, User entity) {
        entity.setUpdateTime(LocalDateTime.now());
    }
}

